<template>
    <el-main>
      <el-row style="margin:20px 0px">
        <el-button style="float:left;margin-right:10px" icon="el-icon-plus" v-if="hasPerm('equipment:equipmentinfo:add')" type="success" size="medium" @click="addEquipment()">新增</el-button>
        <my-Search :searchWay="true" :inputPlaceholder="'器材名称'" @onSearch="getSearchContent"></my-Search>
        <el-upload
          v-if="hasPerm('equipment:equipmentinfo:import')"
          action="#"
          :show-file-list="false"
          accept=".xls,.xlsx"
          :http-request="handleRequest"
          :before-upload="handleBeforeUpload"
          style="display:inline;margin-right:10px"
        >
          <el-button :loading="uploadLoading" type="warning" icon="el-icon-download" size="medium" >导入生成</el-button>
        </el-upload>
        <el-button :loading="downloadLoading" @click="handleDownload" :disabled="selectTableRowId.length<=0 && !downloadLoading" v-if="hasPerm('equipment:equipmentinfo:export')" type="warning" icon="el-icon-upload2" size="medium" >导出数据</el-button>
        <el-button :disabled="selectTableRowId.length<=1" v-if="hasPerm('equipment:equipmentinfo:deletebatch')" type="danger" icon="el-icon-delete-solid" size="medium" @click="deleteEquipmentBatch">批量删除</el-button>
      </el-row>

      <el-table @selection-change="selectTable" :height="tableHeight" row-key="id" ref="equipmentTableData" :data="equipmentTableData" :default-sort = "{prop: 'number', order: 'ascending'}"  stripe border>
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column prop="name" align="center" label="器材名称"></el-table-column>
        <el-table-column prop="local" align="center" label="存放位置"></el-table-column>
        <el-table-column prop="remark" align="center" label="器材简介" show-overflow-tooltip></el-table-column>
        <el-table-column width="120px" sortable prop="buyCost" align="center" label="出售单价">
          <template slot-scope="scope">
            {{scope.row.buyCost | showCost(true)}}
          </template>
        </el-table-column>
        <el-table-column width="120px" sortable prop="rentCost" align="center" label="租借价格">
          <template slot-scope="scope">
            {{scope.row.rentCost | showCost(false)}}
          </template>
        </el-table-column>
        <el-table-column width="120px" sortable prop="number" align="center" label="库存数量"></el-table-column>
        <el-table-column width="120px" prop="category" align="center" label="类别"></el-table-column>
        <el-table-column width="90px" prop="status" align="center" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="editEquipmentStatus(scope.row.id)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column width="200px" align="center"  label="操作">
          <template slot-scope="scope">
            <el-button v-if="hasPerm('equipment:equipmentinfo:edit')" type="primary" icon="el-icon-edit" size="small" @click="editEquipment(scope.row)" >编辑</el-button>
            <el-button v-if="hasPerm('equipment:equipmentinfo:delete')" type="danger" icon="el-icon-delete" size="small" @click="deleteEquipment(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区 -->
      <pagination
      ref="pagination"
      @pagination="getPagination"
      :total="parseInt(totalPage)"
      :page="parseInt(searchCondition.page)"
      :limit="parseInt(searchCondition.pageSize)"
      :pageSizes="paginationSize"
      ></pagination>

      <!-- 新增或编辑弹框 -->
      <my-dialog
        :title="equipmentDialog.title"
        :width="equipmentDialog.width"
        :height="equipmentDialog.height"
        :visible="equipmentDialog.visible"
        @onClose="onClose"
        @onConfirm="onConfirm"
      >
        <div slot="content">
          <el-form
            :model="equipmentFormData"
            ref="equipmentFormRef"
            :rules="rules"
            label-width="96px"
            size="small"
          >
            <el-row>
              <el-col :span="13">
                <el-form-item prop="name" size="small" label="器材名称">
                  <el-input v-model="equipmentFormData.name" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="9" :offset="2">
                <el-form-item prop="cid" size="small" label="器材类别">
                  <el-select
                    style="min-width: 216px;"
                    filterable
                    clearable
                    default-first-option
                    v-model="equipmentFormData.cid"
                    placeholder="点击选择或输入搜索相应类别"
                  >
                    <el-option
                      v-for="item in categories"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="13">
                <el-form-item prop="local" size="small" label="存放位置">
                  <el-input v-model="equipmentFormData.local" clearable maxlength="20" show-word-limit></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="9" :offset="2">
                  <el-form-item prop="number" size="small" label="库存数量">
                    <el-input-number
                      controls-position="right"
                      v-model.number="equipmentFormData.number"
                      :min="0"
                    ></el-input-number>
                  </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="13">
                <el-form-item prop="remark" size="small" label="器材简介">
                  <el-input
                    type="textarea"
                    maxlength="100"
                    show-word-limit
                    v-model="equipmentFormData.remark"
                    :rows="4"
                    resize="none"
                    placeholder="（限100字）"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="9" :offset="2">
                <el-row>
                  <el-form-item prop="buyCost" size="small">
                    <span slot="label">
                      <el-tooltip content="价格为负数时表示非卖品" placement="top">
                        <i class="el-icon-question"></i>
                      </el-tooltip>出售单价
                    </span>
                    <el-input-number
                      v-model.number="equipmentFormData.buyCost"
                      :controls="false"
                      :precision="2"
                      :min="-1"
                      :max="1000"
                    />
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item prop="rentCost" size="small">
                    <span slot="label">
                      <el-tooltip content="价格为负数时表示不可出售" placement="top">
                        <i class="el-icon-question"></i>
                      </el-tooltip>租借价格
                    </span>
                    <el-input-number
                      v-model.number="equipmentFormData.rentCost"
                      :controls="false"
                      :precision="2"
                      :min="-1"
                      :max="1000"
                    />
                  </el-form-item>
                </el-row>
              </el-col>
            </el-row>
            <br/>
            <el-form-item size="small" label="器材图片">
              <el-upload
                :file-list="fileList"
                ref="pic"
                list-type="picture-card"
                :class="showUploadButton ? 'uoloadSty' : 'disUoloadSty'"
                action="#"
                :http-request="requestUpload"
                :on-preview="handlePictureCardPreview"
                multiple
                :limit="5"
                :on-exceed="handleExceed"
                accept=".png,.jpg,.jpeg"
                :before-upload="beforeUpload"
                :on-change="handleChange"
                :on-remove="handleRemove"
                >
                  <i slot="default" class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>

          </el-form>
        </div>
      </my-dialog>
      <el-dialog append-to-body :visible.sync="picsVisible">
        <img width="100%" :src="picsPreviewUrl" alt="">
      </el-dialog>
    </el-main>
</template>

<script>
import {
  getEquipmentListApi,
  addEquipmentApi,
  editEquipmentApi,
  editEquipmentStatusApi,
  addEquipmentBatchApi,
  deleteEquipmentApi,
  deleteEquipmentBatchApi
} from "@/api/equipment";
import {
  uploadPicturesApi,
  getPicturesByBidApi,
  deletePicturesApi,
  deleteAllFilesApi
} from "@/api/pictures";
import { getCategoryApi } from "@/api/category";
import myDialog from "@/components/MyDialog/index";
import mySearch from "@/components/MySearch/index";
import pagination from "@/components/Pagination/index";
export default {
  components: { myDialog,mySearch,pagination },
  data(){
    return {
      //图片上传设置
      picsPreviewUrl: '',
      picsVisible: false,
      showUploadButton: true,
      fileList: [],
      deletePicsList: [],

      //新增或编辑表单验证规则
      rules: {
        name: { required: true, trigger: "blur", message: "请填写器材名称" },
        buyCost: { required: true, trigger: "blur", message: "请填写出售单价" },
        rentCost: { required: true, trigger: "blur", message: "请填写租借价格" }
      },
      //true：编辑 flase :新增
      actionType: "",
      //新增或编辑表单数据域
      equipmentFormData: {
        id:"",
        equipmentNo:"",
        name:"",
        local:"",
        remark:"",
        buyCost: "",
        rentCost: "",
        number:"",
        cid:"",
        status:""
      },
      //新增或编辑弹框属性
      equipmentDialog: {
        title: "",
        width: 924,
        height: 406,
        visible: false,
      },

      //导出excel配置
      //是否正在导出
      downloadLoading: false,
      //导出文件名
      filename: "器材信息表",
      //是否正在导入
      uploadLoading: false,

      //器材列表
      equipmentTableData: [],
      //被选中的行 携带Id
      selectTableRowId: [],
      //被选中的行 携带No
      selectTableRowNo: [],
      //查询条件
      searchCondition :{
        page: 1,
        pageSize: 10,
        cid: '',
        searchContent: ""
      },
      //分页容量
      paginationSize: [5,10,30,50,100,200],
      //查询返回 总记录数
      totalPage: 0,
      //true：编辑 flase :新增
      actionType: "",
      //运动类别
      categories: "",
      //表格高度
      tableHeight: 0,
    }
  },
  created() {
    this.getCategory().then(_=>{
      this.getEquipmentList();
    })
  },
  mounted() {
    this.$nextTick(() => {
      //有页码区就高度多-120
      this.tableHeight = window.innerHeight - 208 - 120;
    });
  },
  methods: {
    // 覆盖默认的上传行为
    requestUpload() {
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") === -1) {
        this.$message.error("文件格式错误，请上传类型如：JPG、PNG后缀的图片！");
        return false;
      }
      if (file.size> 3145728) {
        this.$message.error("请上传大小不超过3MB的图片！");
        return false;
      }
      return true;
    },
    handleExceed(){
      this.$message.info("最多选择上传五张图片，请重新选择！");
    },
    //删除图片
    handleRemove(file,filelist) {
      if(file.status==="success"){
        this.deletePicsList.push(file.id);
      }
      this.isShowUploadButton(filelist.length)
    },
    //提交图片
    handleChange(file,filelist){
      this.isShowUploadButton(filelist.length)
    },
    //预览图片
    handlePictureCardPreview(file) {
      this.picsPreviewUrl = file.url;
      this.picsVisible = true;
    },
    //判断是否显示上传按钮
    isShowUploadButton(listLength){
      if(listLength >= 5){
        this.showUploadButton = false;
      }else{
        this.showUploadButton = true;
      }
    },
    //获取图片
    async getPicturesByBidApi(bid){
      let res = await getPicturesByBidApi({"bid":bid})
      if(res&&res.code==200){
        this.fileList = res.data;
        this.isShowUploadButton(this.fileList.length);
      }
    },
    //上传图片
    async uploadPictures(list,bid){
      let formData = new FormData();
      list.forEach(item=>{
        formData.append("files",item.raw);
      })
      formData.append("bid",bid);
      await uploadPicturesApi(formData);
    },
    //确认删除图片
    async deletePictures(list){
      await deletePicturesApi({ids:list.toString()});
    },
    //修改器材状态
    async editEquipmentStatus(value){
      let res = await editEquipmentStatusApi(value);
      if (res && res.code == 200) {
        //刷新列表
        this.getEquipmentList();
        this.$message.success(res.msg);
      }
    },
    //新增或编辑确认
    onConfirm() {
      let readyUploadList = [];
      this.$refs.pic.uploadFiles.forEach(item=>{
        if(item.status==="ready"){
          readyUploadList.push(item)
        }
      })
      this.$refs.equipmentFormRef.validate(async (valid) => {
        if (valid) {
          let res = null;
          let bid;
          if (this.actionType) {
            //编辑
            res = await editEquipmentApi(this.equipmentFormData);
            bid = this.equipmentFormData.equipmentNo;
            //删除以前的图片
            if(this.deletePicsList.length>0){
              this.deletePictures(this.deletePicsList);
            }
          } else {
            //新增
            res = await addEquipmentApi(this.equipmentFormData);
            bid = res.data
          }
          if (res && res.code == 200) {
            if(readyUploadList.length>0){
              this.uploadPictures(readyUploadList,bid)
            }
            //刷新列表
            this.getEquipmentList();
            this.onClose();
            this.$message.success(res.msg);
          }
        }
      });
    },
    //新增或编辑取消
    onClose() {
      this.equipmentDialog.visible = false;
      this.deletePicsList = [];
      this.isShowUploadButton(this.filelist)
      this.$refs.pic.clearFiles();
    },
    //新增按钮
    addEquipment() {
      this.$resetForm("equipmentFormRef", this.equipmentFormData);
      this.equipmentFormData.buyCost = -1;
      this.equipmentFormData.rentCost = -1;
      this.equipmentDialog.title = "新增器材";
      this.actionType = false;
      this.equipmentDialog.visible = true;
    },
    //编辑按钮
    editEquipment(row) {
      this.$resetForm("equipmentFormRef", this.equipmentFormData);
      //回显图片
      this.getPicturesByBidApi(row.equipmentNo);
      //把当前要编辑的数据复制到数据域，tApi给表单回显
      this.$objCoppy(row, this.equipmentFormData);
      //设置编辑的标识
      this.actionType = true;
      //设置弹框属性
      this.equipmentDialog.title = "编辑器材";
      this.equipmentDialog.visible = true;
    },
    //删除按钮
    async deleteEquipment(row) {
      let confirm = await this.$myconfirm("确定删除器材【"+row.name+"】吗？");
      if (confirm) {
        let res = await deleteEquipmentApi({id: row.id});
        if (res && res.code == 200) {
          if(this.searchCondition.pageSize ==1 || this.totalPage % this.searchCondition.pageSize ==1){
            this.searchCondition.page-=1;
          }
          //删除本地及数据库的图片
          await deleteAllFilesApi({bids: row.equipmentNo});
          //刷新列表
          this.getEquipmentList();
          this.$message.success(res.msg);
        }
      }
    },
    //获取选择表格项
    selectTable(selection){
      this.selectTableRowId = [];
      this.selectTableRowNo = [];
      selection.forEach(item=>{
        this.selectTableRowId.push(item.id);
        this.selectTableRowNo.push(item.equipmentNo);
      })
    },
    //批量删除
    async deleteEquipmentBatch() {
      let confirm = await this.$myconfirm("此操作不可逆！确定删除这些器材吗？");
      if (confirm) {
        let deleteArray = this.selectTableRowId.toString();
        let deleteList = this.selectTableRowNo.toString();
        let res = await deleteEquipmentBatchApi({ids:deleteArray});
        if(res && res.code == 200){
          if(this.totalPage % this.searchCondition.pageSize ==this.selectTableRowId.length){
            this.searchCondition.page-=1;
          }
          //删除本地及数据库的图片
          await deleteAllFilesApi({bids: deleteList});
          this.getEquipmentList();
          this.$message.success(res.msg);
        }
      }
    },
    //导出数据
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['序号','器材编号', '器材名称', '器材位置','器材介绍', '出售单价', '租借价格', '库存数量', '类别']
        const filterVal = ['id','equipmentNo', 'name', 'local','remark', 'buyCost', 'rentCost', 'number', 'category']
        const list = this.equipmentTableData
        const data = this.formatJson(filterVal, list)

        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename+'_'+new Date().getTime(),
        })

        this.$refs.equipmentTableData.clearSelection()
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    //导入数据
    async handleRequest({ file }){
      this.uploadLoading = true
      const formData = new FormData();
      formData.append('file',file);
      let res = await addEquipmentBatchApi(formData).finally(this.uploadLoading = false)
      if(res&&res.code==200){
        this.$message.success(res.msg);
        this.getEquipmentList();
      }
    },
    handleBeforeUpload(file){
      if (file.name.slice(-3) != "xls" && file.name.slice(-4) != "xlsx"){
        this.$message.error("文件格式错误，请导入格式为xls、xlxs的文件！");
        return false;
      }
      return true;
    },
    //内容查询
    getSearchContent(val){
      this.searchCondition.searchContent = val;
      this.getEquipmentList();
    },
    //分页查询getPagination
    getPagination(val){
      this.searchCondition.page = val.page;
      this.searchCondition.pageSize = val.limit;
      this.getEquipmentList();
    },
    //获取器材列表
    async getEquipmentList() {
      let res = await getEquipmentListApi(this.searchCondition);
      if (res && res.code == 200) {
        this.totalPage = res.data.total;
        let copyList = res.data.records
        copyList.forEach((item)=>{
          //处理类别格式
          if(item.cid==null) {
            item.category = '其它'
          }else{
            this.categories.forEach(index => {
              if(index.id==item.cid){
                item.category = index.label
              }
            });

          }
        })
        this.equipmentTableData = copyList;
      }
    },
    //获取运动类型
    async getCategory() {
      let res = await getCategoryApi();
      if(res && res.code == 200) {
        this.categories = res.data;
      }
    }
  },
  filters: {
    showCost(val,flag){
      if(flag){
        if(val<0){
          return '非卖品'
        }else if(val==0){
          return '赠送品'
        }else if(val>0){
          return val+'元'
        }
      }else{
        if(val<0){
          return '不可租借'
        }else if(val==0){
          return '免费'
        }else if(val>0){
          return val+'元'
        }
      }
    },
  }
}
</script>

<style scoped lang="scss">
  .uoloadSty ::v-deep .el-upload--picture-card{
    width: 148px;
    height: 148px;
    line-height: 146px
    }
  .disUoloadSty ::v-deep .el-upload--picture-card{
    display:none;
    }
  .uoloadSty ::v-deep .el-upload-list__item {
    transition: none !important;
  }
  .disUoloadSty ::v-deep .el-upload-list__item {
    transition: none !important;
  }
</style>
